from odoo import fields, models, api, _
from odoo.osv import expression

class UomUom(models.Model):
    _inherit = 'uom.uom'

    @api.model
    def name_search(self, name, args=None, operator='ilike', limit=100):
        limit_purchase = self.env.context.get('limit_purchase', False)
        uom_id = self.env.context.get('uom_id', '')
        if limit_purchase and uom_id:
            uom = self.env['uom.uom'].sudo().browse(uom_id)
            args = expression.AND([args, [('category_id', '=', uom.category_id.id)]])
        return super().name_search(name, args, operator, limit)

    @api.model
    def read_group(self, domain, fields, groupby, offset=0, limit=None, orderby=False, lazy=True):
        limit_purchase = self.env.context.get('limit_purchase', False)
        uom_id = self.env.context.get('uom_id', '')
        if limit_purchase and uom_id:
            uom = self.env['uom.uom'].sudo().browse(uom_id)
            domain = expression.AND([domain, [('category_id', '=', uom.category_id.id)]])
        return super().read_group(domain, fields, groupby, offset=offset, limit=limit, orderby=orderby, lazy=lazy)

    @api.model
    def search_read(self, domain=None, fields=None, offset=0, limit=None, order=None):
        limit_purchase = self.env.context.get('limit_purchase', False)
        uom_id = self.env.context.get('uom_id', '')
        if limit_purchase and uom_id:
            uom = self.env['uom.uom'].sudo().browse(uom_id)
            domain = expression.AND([domain, [('category_id', '=', uom.category_id.id)]])
        return super().search_read(domain=domain, fields=fields, offset=offset, limit=limit, order=order)

    @api.model
    def web_search_read(self, domain, specification, offset=0, limit=None, order=None, count_limit=None):
        limit_purchase = self.env.context.get('limit_purchase', False)
        uom_id = self.env.context.get('uom_id', '')
        if limit_purchase and uom_id:
            uom = self.env['uom.uom'].sudo().browse(uom_id)
            domain = expression.AND([domain, [('category_id', '=', uom.category_id.id)]])
        return super().web_search_read(domain, specification, offset=offset, limit=limit, order=order, count_limit=count_limit)

    @api.onchange('uom_id', 'categ_id')
    def _get_uom_po_domain(self):
        if self.categ_id.limit_purchase:
            if self.uom_po_id.category_id != self.uom_id.category_id:
                self.uom_po_id = False
            domain = [('category_id', '=', self.uom_id.category_id.id)]
        else:
            domain = []
        return {
            'domain': {
                'uom_po_id': domain
            }
        }